﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TpWeb.Domain.BizObj;
using TpWeb.Domain.Repositories;

namespace TpWeb.Dal.Repositories
{
    internal class FiasRepository : IFiasRepository
    {
        private DbContext _context;


        public FiasRepository(DbContext context)
        {
            _context = context;
        }

        private IEnumerable<TEntity> SelectArrdObj<TEntity>(string term, int count, int? level, string guid = null, string parentGuid = null, int? regCode = null)
        {
            return _context.Database.SqlQuery<TEntity>("exec GetFiasObject @p0,@p1,@p2,@p3,@p4,@p5", term, count, level, guid, parentGuid, regCode);
        }

        public IEnumerable<AddrObject> SelectRegions(string term, int count, string guid = null, string parentGuid = null)
        {
            return SelectArrdObj<AddrObject>(term, count, 1, guid);
        }

        public IEnumerable<AddrObject> SelectDistricts(string term, int count, string guid = null, string parentGuid = null)
        {
            return SelectArrdObj<AddrObject>(term, count, 3, guid, parentGuid);
        }

        public IEnumerable<AddrObject> SelectTowns(string term, int count, string guid = null, string parentGuid = null, int? regCode = null)
        {
            return SelectArrdObj<AddrObject>(term, count, 4, guid, parentGuid, regCode);
        }

        public IEnumerable<AddrObject> SelectLocality(string term, int count, string guid = null, string parentGuid = null, int? regCode = null)
        {
            return SelectArrdObj<AddrObject>(term, count, 6, parentGuid: parentGuid, regCode: regCode);
        }

        public IEnumerable<AddrObject> SelectStreets(string term, int count, string guid = null, string parentGuid = null, int? regCode = null)
        {
            return SelectArrdObj<AddrObject>(term, count, 7, parentGuid: parentGuid, regCode: regCode);
        }

        public IEnumerable<AddrObject> SelectPostalCodes(int term, int count)
        {
            throw new NotImplementedException();
        }

        public AddrObject GetAddrObject(string guid)
        {
            return SelectArrdObj<AddrObject>(null, 1, null, guid).SingleOrDefault();
        }
    }
}
